<?php
/**
 * Render ExtJs Form Configuration
 *
 * @category	Itc
 * @package		Itc_ExtForm
 * @author		Sergey Kage_no_Neko Yakovlev
 * @version		1.0
 * @date		26.09.2012
 *
 */
class Itc_Ext_Form extends Zend_Form {
    
    /**
     * create form config object
     * 
     * @return array/json
     */
    public function renderExtFormObj($json = true){
    	$fields = $this->renderExtFormFieldsObj(false);
    	$form = $this->_formToExtJs($fields);
    	if($json){
    		$form = json_encode($form);
    	}
    	return $form;
    }
    
	/**
     * create form fields config objects
     * 
     * @return array/json
     */
    public function renderExtFormFieldsObj($json = true){
    	$elements = $this->getElements();
    	$fields = array();
    	foreach($elements as $key => $element){
    		$fields[] = $this->_elementToExtJs($element);
    	}
    	if($json){
    		$fields = json_encode($fields);
    	}
    	return $fields;
    }
    
	protected function _formToExtJs($fields = array()){
		$conf = array(
			'xtype' => 'form',
			'items' => $fields
		);
		foreach($this->getAttribs() as $key => $value){
    		$conf[$key] = $value;
    	}
    	return $conf;
    }
    
    protected function _elementToExtJs($element){
    	$allow_types = array('text','hidden','textarea');
    	$type = preg_replace('/^form(.+)$/', '$1', strtoupper($element->helper));
    	if(!in_array($type, $allow_types)){
    		require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Itc_Ext_From got unsupported element');
    	}
    	$conf = array(
    		'xtype' => $type,
    		'allowBlank' => !$element->_required
    	);
    	foreach($element->getAttribs() as $key => $value){
    		$conf[$key] = $value;
    	}

    	$vtype = $this->_getElementValidatorToExtJs($element);
    	if(count($vtype) > 1){
    		$conf['vtype'] = 'multiple';
    		$conf['vtypedata'] = $vtype;
    	}elseif(count($vtype) == 1){
    		$conf['vtype'] = $vtype[0];
    	}
    	return $conf;
    }
    
    protected function _getElementValidatorToExtJs($element){
    	$conf = array();
    	foreach($element->getValidators() as $key => $value){
    		$conf[] = $key;
    	}
    	
    	return $conf;
    }
}